<template>
  <el-dialog v-bind="$attrs" @opened="opened">
    <div ref="editor"></div>
    <template #footer>
      <slot :wordhtml="content"></slot>
    </template>
  </el-dialog>
</template>
<script>
  import { onMounted, onBeforeUnmount, ref, reactive } from 'vue'
  import WangEditor from 'wangeditor'
  import UploadServlet from '@/api/UploadServlet'

  export default {
    name: 'ZwangEditor',
    props: ['wordhtml'],
    setup(props) {
      const editor = ref()
      const content = reactive({
        html: '',
        text: '',
      })
      let instance
      onMounted(() => {})

      onBeforeUnmount(() => {
        instance.destroy()
        instance = null
      })

      const syncHTML = () => {
        content.html = instance.txt.html()
      }
      const opened = () => {
        instance = new WangEditor(editor.value)
        // 配置菜单栏，设置不需要的菜单
        instance.config.excludeMenus = [
          'emoticon',
          'link',
          'video',
          'table',
          'code',
        ]
        instance.config.showFullScreen = false
        instance.config.uploadImgMaxLength = 1
        // instance.txt.html(props.wordhtml)
        instance.config.customUploadImg = function (resultFiles, insertImgFn) {
          if (resultFiles.length != 0) {
            UploadServlet(resultFiles[0]).then((par) => {
              insertImgFn(par)
            })
          }
        }

        Object.assign(instance.config, {
          onchange() {
            syncHTML()
          },
        })

        instance.create()
        instance.txt.html(`<div>${props.wordhtml}</div>`)
      }
      return {
        opened,
        syncHTML,
        editor,
        content,
        instance,
      }
    },
    data() {
      return {}
    },
    mounted() {},
    methods: {},
  }
</script>
